
// 引入请求函数
import { asyncGetUserInfo, asyncLogins, asyncLogoOut } from "@/api/login";
import router from "@/router";
import { anyRoutes, asyncRoutes, constantRoutes } from "@/router/router";
import { getToken, removeToken, setToken } from "@/utils/token";

// 引入深拷贝
import cloneDeep from 'lodash/cloneDeep';
// 筛选用户的异步路由
const filterAsyncRoutes = (asyncRoutes, routes) => {
  return asyncRoutes.filter(item => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes);
      }
      return true;
    }
  });
};
export default {
  // 开启命名空间
  namespaced: true,
  actions: {
    // 请求登录的回调
    async login({ commit }, phone) {
      let res = await asyncLogins(phone);
      // console.log(res);
      res.code == 20000 && commit('LOGIN', res.data.token);
    },
    // 请求用户信息的回调
    async getInfo({ commit, state }) {
      let res = await asyncGetUserInfo();
      // console.log(res, '用户信息');
      res.code == 20000 && commit('GETTINFO', res.data);
      // 筛选异步路由
      let userAsyncRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), res.data.routes);
      // console.log(userAsyncRoutes, '异步路由');
      // 合并路由
      const allRoutes = [...constantRoutes, ...userAsyncRoutes, anyRoutes];
      // console.log(res.data.routes, 'kuyou ');
      // console.log(allRoutes, 'all');
      state.routes = allRoutes;
      // // 动态添加路由
      router.addRoutes([...userAsyncRoutes, anyRoutes]);

    },
    // 退出登录的回调
    async logoOut({ commit, state }) {
      let res = await asyncLogoOut();
      res.code == 20000 && removeToken();
      state.name = '';
      state.routes = [];
      state.asyncRoutes = [];
    }
  },
  mutations: {
    // 登录的信息
    LOGIN(state, value) {
      state.token = value;
      setToken(state.token);
    },
    // 用户的信息
    GETTINFO(stata, value) {
      // 用户名字
      stata.name = value.name;
      // 用户头像
      stata.avatar = value.avatar;
      // 路由列表
      stata.routes = value.routes;
      // 按钮列表
      stata.buttons = value.buttons;
      // 身份列表
      stata.roles = value.roles;
    }

  },
  state: {
    token: getToken(),
    //存储名字
    name: "",
    //存储头像
    avatar: "",
    // 存储全部路由
    routes: [],
    // 存储全部按钮
    buttons: [],
    // 新增的动态路由
    asyncRoutes: [],
    // 身份列表
    roles: []

  }
};
